package main

import (
	"crypto/md5"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

type Message struct {
	Name string
	Body string
	Time int64
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "This is a lidejin")
}

func lidejin(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "This is a apple")
}

func lidejin2(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "lidejin is a apple")
}

func macro(w http.ResponseWriter, t *http.Request) {
	if t.Method == "GET" {
		fmt.Fprint(w, "lidejin")
	} else {
		fmt.Fprint(w, "lidejin111")
	}
}

func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method", r.Method)
	if r.Method == "GET" {
		// 返回页面
	} else {
		// 传输文件
	}
}

func upload1(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) // 获取请求的方法
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) // 此处假设当前目录下已存在test目录
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}

}

func timeHandler(format string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tm := time.Now().Format(format)
		w.Write([]byte("The is a apple" + tm))
	})
}

func main() {
	http.HandleFunc("/upload", upload)
	http.HandleFunc("/", sayhelloName)
	http.HandleFunc("/lidejin", lidejin)
	http.HandleFunc("/lidejin1", lidejin2)
	http.Handle("/time", timeHandler(time.RFC1123))
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
